package com.jinxin.platform.cdperprotypay.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.jinxin.platform.cdperprotypay.excel.data.MeterDatas;

import com.jinxin.platform.cdperprotypay.mapper.MeterDataMapper;
import com.jinxin.platform.cdperprotypay.pojo.bo.SysUser;
import com.jinxin.platform.cdperprotypay.pojo.domain.MeterData;
import com.jinxin.platform.cdperprotypay.support.ModularSupport;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 读取导入表数据并映射解析
 *
 * @author zhangsong 2020/5/14
 */
@Slf4j
@Component
@Data
public class MeterDataReadListener extends AnalysisEventListener<MeterDatas> {

    @Resource
    private MeterDataMapper meterDataMapper;
    @Resource
    private ModularSupport modularSupport;

    public static MeterDataReadListener meterDataReadListener;
    public static MeterDataReadListener meterDataReadListener1;

    public String villageId;
    public Map<String, String> map = new ConcurrentHashMap<>();


    @PostConstruct
    public void init() {
        meterDataReadListener = this;
        meterDataReadListener1 = this;
        meterDataReadListener.meterDataMapper = this.meterDataMapper;
        meterDataReadListener1.modularSupport = this.modularSupport;
    }

    public static int insert(MeterData meterData) {
        return meterDataReadListener.meterDataMapper.insert(meterData);
    }

    public static int update(MeterData meterData) {
        return meterDataReadListener.meterDataMapper.update(meterData);
    }

    public static List<MeterData> queryAll(MeterData meterData) {
        return meterDataReadListener.meterDataMapper.queryAll(meterData);
    }

    public static SysUser getUser() {
        return meterDataReadListener1.modularSupport.getCurrentUser();
    }

    /**
     * 每隔3000条存储数据库
     */
    private static final int BATCH_COUNT = 3000;
    private List<MeterDatas> list = new ArrayList<>();

    public MeterDataReadListener() {
        super();
    }

    public MeterDataReadListener(String villageId) {
        super();
        this.villageId = villageId;
    }

//    public MeterDataReadListener(String customerId) {
//        super();
//        this.customerId = customerId;
//    }

    @Override
    public void invoke(MeterDatas data, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        boolean flag = false;
        if (data.getVillageId() == null || data.getVillageId().equals("")) {
            map.put("msg", "文件异常，小区id不能为空");
            list.clear();
            throw new RuntimeException();
        }

        if (data.getRoomId() == null || data.getRoomId().equals("")) {
            map.put("msg", "文件异常，房间id不能为空");
            list.clear();
            throw new RuntimeException();
        }

        if (data.getItemsId() == null || data.getItemsId().equals("")) {
            map.put("msg", "文件异常，项目id不能为空");
            list.clear();
            throw new RuntimeException();
        }

        if (data.getMeterStime() == null || data.getMeterStime().equals("") || data.getMeterEtime() == null || data.getMeterEtime().equals("")) {
            map.put("msg", "文件异常，开始/结束时间不能为空");
            list.clear();
            throw new RuntimeException();
        }

        if (data.getTimes() == null || data.getTimes().equals("")) {
            map.put("msg", "文件异常，倍率不能为空");
            list.clear();
            throw new RuntimeException();
        }

        if (data.getMeterSdata() == null || data.getMeterSdata().equals("") || data.getMeterEdata() == null || data.getMeterEdata().equals("")) {
            map.put("msg", "文件异常，起/止码不能为空");
            list.clear();
            throw new RuntimeException();
        }

        try {
            if (Integer.parseInt(data.getMeterSdata()) > Integer.parseInt(data.getMeterEdata())) {
                map.put("msg", "文件异常，起码应小于止码");
                list.clear();
                throw new RuntimeException();
            }
            Integer.parseInt(data.getTimes());
        } catch (Exception e) {
            list.clear();
            flag = true;
        }

        if (flag) {
            map.put("msg", "文件异常，起/止码、倍率请填写数字");
            list.clear();
            throw new RuntimeException();
        }

        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            saveData(list);
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData(list);
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData(List<MeterDatas> list) {
        log.info("{}条数据，开始存储数据库！", list.size());

        SysUser currentUser = getUser();
        for (MeterDatas bl : list) {
            MeterData meterData = new MeterData();
            BeanUtils.copyProperties(bl, meterData);
            meterData.setMeterItems(bl.getItemsId());
//            meterData.setVillageId(this.villageId);
            //验重
            MeterData meter = new MeterData();
            List<MeterData> dataList = new ArrayList<>();

            Double c = (Double.parseDouble(bl.getMeterEdata()) - Double.parseDouble(bl.getMeterSdata())) * Double.parseDouble(bl.getTimes());
            meterData.setConsumption(String.format("%.2f", c));
            meterData.setCreater(currentUser.getUserName());
            meterData.setCreateTime(new Date());

            if (bl.getMeterStime() != null && bl.getMeterEtime() != null) {
                meter.setRoomId(meterData.getRoomId());
                meter.setMeterStime(meterData.getMeterStime());
                meter.setMeterEtime(meterData.getMeterEtime());
                meter.setMeterItems(bl.getItemsId());
                dataList = queryAll(meter);

                meterData.setStatus("1");
            } else {
                meterData.setStatus("2");
            }

            if (dataList.size() == 1) {
                meterData.setId(dataList.get(0).getId());
                update(meterData);
            } else {
                insert(meterData);
            }

        }

        log.info("存储数据库成功！");
    }
}
